package com.changeover.service;

import static com.google.common.base.Preconditions.checkArgument;

import java.text.MessageFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.changeover.dao.IUserDao;
import com.changeover.gwt.shared.model.LoginInfo;
import com.changeover.gwt.shared.model.User;
import com.changeover.gwt.shared.validation.LoginFieldVerifier;
import com.google.common.base.Objects;

@Service
public class LoginService implements ILoginService {

    @Autowired
    private IUserDao userDao;

    @Override
    @Transactional
    public void checkLoginInfo(LoginInfo loginInfo) throws IllegalArgumentException {
        String login = loginInfo.getLogin();
        String password = loginInfo.getPassword();

        checkArgument(LoginFieldVerifier.isValidLogin(login), "Login must be at least 4 characters long");
        checkArgument(LoginFieldVerifier.isValidPassword(password),
            "Password must be at least 6 characters long");

        List<User> users = userDao.getAll();
        for (User user : users) {
            if (Objects.equal(user.getName(), login) && Objects.equal(user.getPassword(), password)) {
                return;
            }
        }
        
        checkArgument(false, MessageFormat.format("User ''{0}'' not found", login));
    }

}
